package com.tvserials.notification.parser;

import com.tvserials.notification.dto.Episode;
import com.tvserials.notification.dto.Serial;
import com.tvserials.notification.exceptions.NetworkConnectionException;
import com.tvserials.notification.exceptions.PageParseException;
import com.tvserials.notification.utils.VOUtils;
import com.tvserials.notification.vo.SourceType;
import com.tvserials.notification.vo.TvEpisodeFilterVO;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by oleksandr.dokienko on 4/16/2014.
 */
public class AllHtmlPageParser implements PageParser {

    private List<PageParser> parsers = Arrays.asList(PageParserFactory.getPageParser(SourceType.LOST_FILM),
            PageParserFactory.getPageParser(SourceType.NEW_STUDIO), PageParserFactory.getPageParser(SourceType.SEASON_VAR));

    public void setParsers(List<SourceType> sourceTypes) {
        parsers.clear();
        for (SourceType type : sourceTypes) {
            parsers.add(PageParserFactory.getPageParser(type));
        }
    }

    @Override
    public List<Episode> parsePage(TvEpisodeFilterVO filterVO) throws NetworkConnectionException, PageParseException {
        ArrayList<Episode> episodes = new ArrayList<Episode>();
        for (PageParser pageParser : parsers) {
            List<Episode> result = new ArrayList<Episode>();
            try {
                result = pageParser.parsePage(filterVO);
            } catch (Exception e) {
                //TODO add logging
                //Log.w("Parser", "Failed to get data from:" + pageParser.getSourceType(), e);
            }
            if (result != null) {
                episodes.addAll(result);
            }

        }
        return VOUtils.sortByDate(episodes);
    }

    @Override
    public List<Serial> parseSerialsList() throws NetworkConnectionException {
        List<Serial> serials = new ArrayList<Serial>();
        for (PageParser pageParser : parsers) {
            List<Serial> result = pageParser.parseSerialsList();
            if (result != null) {
                serials.addAll(result);
            }
        }
        return serials;
    }

    @Override
    public SourceType getSourceType() {
        return SourceType.ALL;
    }
}
